# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict
from datetime import timedelta

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import local_now

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '50017': {  # loki 支付宝
        'API_KEY': 'KcFa01Yu9j88pdvFNWtuX2cjiw1Adorb',
        'gateway': 'http://119.23.202.142/trade/pay',
        'query_gateway': 'http://119.23.202.142/trade/query',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def smart_utf8(strdata):
    ''' strdata转换为utf-8编码字符串'''
    return strdata.encode('utf-8') if isinstance(strdata, unicode) else str(strdata)


def generate_sign(info, key):
    keys = info.keys()
    keys.sort()
    tmp = []
    for k in keys:
        if k not in ['sign'] and info[k]:
            tmp.append("%s=%s" % (smart_utf8(k), smart_utf8(info[k])))
            tmpStr = '&'.join(tmp)
    tmpStr += "&%s=%s" % ('key', smart_utf8(key))
    md5 = hashlib.md5()
    md5.update(tmpStr)
    ret = md5.hexdigest().upper()
    return ret


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("zhifubangpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


# 10001:支付宝
def _get_pay_type(service):
    return '10001'


def _get_str(s, start, end):
    p1 = s.index(start)
    p2 = s.index(end, p1 + len(start))
    if p2 > p1:
        return s[p1 + len(start): p2]
    else:
        return ''


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('mchid', app_id),
        ('out_trade_no', str(pay.id)),
        ('total_fee', str(int(pay_amount * 100))),
        ('time_start', local_now().strftime("%Y%m%d%H%M%S")),
        ('goods_name', 'charge'),
        ('trade_type', _get_pay_type(service)),
        ('time_expire', (local_now() + timedelta(minutes=25)).strftime("%Y%m%d%H%M%S")),
        ('notify_url', '{}/pay/api/{}/zhifubangpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("zhifubangpay create data : %s", json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("zhifubangpay create charge rsp data: %s, %s", str(pay.id), response.text)
    return {'charge_info': json.loads(response.text)['data']['pay_params']}


# SUCCESS
def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("zhifubangpay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['out_trade_no']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('zhifubangpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['pay_status'])
    trade_no = data['trade_no']
    total_fee = float(data['total_fee']) / 100.0

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    # 支付状态 → 1:待支付;
    # 2:支付中(支付成功，未通知); 3:支付成功;
    # 4:支付失败;
    if trade_status in ['2', '3']:
        _LOGGER.info('zhifubangpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('mchid', app_id),
        ('out_trade_no', str(pay_id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info('zhifubangpay query data:%s', parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info('zhifubangpay query rsp:%s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)['data'][0]
        trade_status = str(data['pay_status'])
        trade_no = str(data['trade_no'])
        total_fee = float(data['total_fee']) / 100.0

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        # 支付状态 → 1:待支付;
        # 2:支付中(支付成功，未通知); 3:支付成功;
        # 4:支付失败;
        if trade_status in ['2', '3']:
            _LOGGER.info('zhifubangpay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            res = order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                           total_fee, trade_no, extend)
            if res:
                # async notify
                async_job.notify_mch(pay_order.id)
            print("order process successfully. %s" % pay_order.id)
    else:
        _LOGGER.warn('zhifubangpay data error, status_code: %s', response.status_code)
